package com.sgj.springcloud.controller;

import com.sgj.springcloud.entities.CommonResult;
import com.sgj.springcloud.entities.Payment;
import com.sgj.springcloud.enums.ResEnum;
import com.sgj.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 沈国纪
 * @date 2021/5/4 12:00
 */
@RestController
@Slf4j
public class PaymentController {

	@Autowired
	private PaymentService paymentService;

	@Value("${server.port}")
	private String serverPort;

	/**
	 * 新建订单
	 * @param payment
	 * @return
	 */
	@PostMapping("/payment/create")
	public CommonResult create(@RequestBody Payment payment) {
		int result = paymentService.create(payment);
		log.info("插入结果 {}", result);

		if (result > 0) {
			return new CommonResult(ResEnum.SUCCESS_INSERT.getCode(), ResEnum.SUCCESS_INSERT.getMessage() +
					"serverPort：" + serverPort, result);
		} else {
			return new CommonResult(ResEnum.FAIL_INSERT.getCode(), ResEnum.FAIL_INSERT.getMessage(), null);
		}
	}

	/**
	 * 获取订单
	 * @param id
	 * @return
	 */
	@GetMapping("/payment/get/{id}")
	public CommonResult getPaymentById(@PathVariable("id") Long id) {
		Payment payment = paymentService.getPaymentById(id);
		log.info("查询结果 {}", payment);

		if (Objects.nonNull(payment)) {
			return new CommonResult(ResEnum.SUCCESS_SEARCH.getCode(), ResEnum.SUCCESS_SEARCH.getMessage() +
					"serverPort：" + serverPort, payment);
		} else {
			return new CommonResult(ResEnum.FAIL_SEARCH.getCode(),
					ResEnum.FAIL_SEARCH.getMessage() + ",查询ID为:" + id, null);
		}
	}

	@GetMapping("/payment/lb")
	public String getPaymentLB() {
		return serverPort;
	}

	@GetMapping("/payment/feign/timeout")
	public String paymentFeignTimeout() {
		// 暂停几秒钟线程
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return serverPort;
	}
}
